package cn.gailvlun.gll.util

import java.util.*


class PlayerTimer {
    private val timer: Timer
    private var uiTask: TimerTask? = null
    private var countTask: TimerTask? = null

    var mOnPlayerTimerListener : OnPlayerTimerListener? = null

    constructor() {
        this.timer = Timer()

        initTimeTask()
    }

    private fun initTimeTask() {
        uiTask = object : TimerTask() {
            override fun run() {
                mOnPlayerTimerListener?.onTick(System.currentTimeMillis() - relativeStartTime!!)
            }

        }
        countTask = object : TimerTask(){
            override fun run() {
                uiTask?.cancel()
                mOnPlayerTimerListener?.onFinish(mDuration!!)
            }

        }
    }

    private var mDuration: Long? = null
    private var initStartTime: Long? = null

    private var relativeStartTime: Long? = null
    private var lastPauseTime: Long? = null

    fun start(milliseconds: Long) {
        mDuration = milliseconds
        initStartTime = System.currentTimeMillis()
        relativeStartTime = initStartTime

        timer.schedule(uiTask, 0, 100)
        timer.schedule(countTask, mDuration!!)
    }

    fun pause() {
        lastPauseTime = System.currentTimeMillis()
        uiTask?.cancel()
        countTask?.cancel()
    }

    fun resume() {

        relativeStartTime = System.currentTimeMillis() - lastPauseTime?.minus(relativeStartTime!!)!!

        initTimeTask()
        timer.schedule(uiTask, 0, 100)
        timer.schedule(countTask, mDuration!! - (System.currentTimeMillis() - relativeStartTime!!))
    }

    fun restart() {
        mOnPlayerTimerListener?.onTick(0)

        initTimeTask()
    }

    fun clear(){
        lastPauseTime=null
        uiTask?.cancel()
        countTask?.cancel()

    }
}

interface OnPlayerTimerListener {
    fun onTick(duration: Long)
    fun onFinish(mDuration: Long)
}